package com.qf.fmall2204.shiro;

import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.jwt.JWT;
import com.qf.fmall2204.constants.Constants;
import com.qf.fmall2204.wxpay.MyWexinConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Set;

/**
 * 自定义shiro过滤器
 */
@Component("jwt")
@Slf4j
public class TokenFilter extends AccessControlFilter {
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {

        // 检查请求头中是否携带了token
        HttpServletRequest req = (HttpServletRequest) request;

        // 注意，小坑，需要判断一下当前的请求是不是浏览器发的 OPTIONS 请求，如果是，直接放行
        if (req.getMethod().equals(HttpMethod.OPTIONS.toString())) {
            return true;
        }

        String token = req.getHeader("token");

        if (token==null){
            log.debug("请求{}没有携带token，不允许通过!",req.getRequestURL());
            return false; // 请求就此打住
        }

        // 检查token是否合法
        boolean result = checkToken(token);
        if (result){
            log.debug("请求{}token有效，通过!",req.getRequestURL());
            return true;
        }else {
            log.debug("请求{}token无效，不允许通过!",req.getRequestURL());
            return false;
        }
    }

    /**
     * token 校验逻辑
     * @param token
     * @return
     */
    private boolean checkToken(String token) throws Exception {

        JWT jwt = JWT.of(token).setKey(Constants.SIGN_KEY.getBytes());

        boolean validate = jwt.validate(0);

        return validate;

    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        return false;
    }
}
